<?php

class sfWidgetFormSelectRadioFlickrPhoto extends sfWidgetFormSelectRadio
{
    protected function configure($options = array(), $attributes = array())
    {
        parent::configure($options, $attributes);

        $this->setOption('class', 'thumbnails form-gallery');
        $this->setOption('translate_choices', false);
        $this->addOption('selected',false);
    }

    public function render($name, $value = null, $attributes = array(), $errors = array())
    {
        if ('[]' != substr($name, -2))
        {
            $name .= '[]';
        }

        $choices = $this->getChoices();

        return $this->formatChoices($name, $value, $choices, $attributes);
    }

    protected function formatChoices($name, $value, $choices, $attributes)
    {
        $inputs = array();
        foreach ($choices as $photo)
        {
            $baseAttributes = array(
                'name'  => substr($name, 0, -2),
                'type'  => 'radio',
                'value' => self::escapeOnce($photo['id']),
                'id'    => $id = $this->generateId($name, self::escapeOnce($photo['id'])),
            );

            if (strpos(strval($this->getOption('selected') === false ? 0 : $this->getOption('selected')),strval($photo['id'])) !== false)
            {
                $baseAttributes['checked'] = 'checked';
            }

            $inputs[$id] = array(
                'input' => $this->renderTag('input', array_merge($baseAttributes, $attributes)),
                'label' => $this->renderContentTag('label',
                    #'<ul class="thumbnail-actions"><li>'.$photo['title'].'</li></ul>' .
                        $this->renderContentTag('img', '', array('src' => 'http://farm'.$photo['farm'].'.staticflickr.com/'.$photo['server'].'/'.$photo['id'].'_'.$photo['secret'].'_q.jpg', 'title' => $photo['title'])),
                    array('for' => $id, 'class' => 'thumbnail')).$photo['title'],
            );
        }

        return call_user_func($this->getOption('formatter'), $this, $inputs);
    }

    public function formatter($widget, $inputs)
    {
        $rows = array();
        $i =0;
        $html ='';
        foreach ($inputs as $input)
        {
            if($i%5 == 0)
                $html .= '<ul class="'.$this->getOption('class').'" >';

            $rows[] = $this->renderContentTag('li', $input['input'].$input['label'], array('class'=>'span2'));
            $html .= $this->renderContentTag('li', $input['input'].$input['label'], array('class'=>'span2'));

            if($i%5 == 4)
                $html .= '</ul>';
            $i++;
        }

        #return !$rows ? '' : $this->renderContentTag('ul', implode($this->getOption('separator'), $rows), array('class' => $this->getOption('class')));
        return !$rows ? '' : $html;
    }
}
